package com.jslx.interceptorbase.loginInterceprotphone;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jslx.anno.login.JSLXLogin;
import com.jslx.pojo.ErroMessage;
import com.jslx.pojo.Users;
import com.jslx.utils.RedisTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登入拦截器
 *
 * @author HYL
 * @create 2017-06-15 下午3:40
 **/
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    ErroMessage erroMessage;

    @Autowired
    private RedisTools redisTools;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            try {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
                Class<?> clazz = method.getDeclaringClass();
                if (clazz.isAnnotationPresent(JSLXLogin.class)||method.isAnnotationPresent(JSLXLogin.class)) {

                    if (!isLogin(request)) {//需要验证登入，从缓存中获取用户看看是否为空
                        //用户未登入
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("status",2);
                        jsonObject.put("message",erroMessage.erroStatusMessage.get(2));
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(jsonObject.toJSONString());
                        return false;
                    }else {
                        return true;
                    }
                }else {
                    return true;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;
    }
    /**
     * 查看用户是否登入
     */
    public boolean isLogin(HttpServletRequest request){
        String sessionId = request.getSession().getId();
        String value = redisTools.getValue(sessionId);
        if (value != null) {
            Users user = JSON.parseObject(value, Users.class);
            request.setAttribute("user",user);
            return true;
        }
        return false;
    }
}
